package com.neusoft.chenhanhua.wh0913;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Maincal2 extends JFrame {
	public static void main(String[] args) {
		new Maincal2();
	}
	public Maincal2(){
		setSize(450, 550);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setTitle("东软计算器");
		// 居中显示
		setLocationRelativeTo(null);
		// 设置布局管理器，使用绝对布局
		setLayout(null);
		// 添加一个文本显示框
		JLabel lbResult = new JLabel("0");
		// 设置控件的位置
		lbResult.setBounds(0, 0, 400, 100);
		// 添加到面板或窗口中
		add(lbResult);
		String [] names= {"1","2","3","+","4","5","6","-","7","8","9","*","c","0","=","/"};
		int[] xs = { 0, 100, 200, 300, 0, 100, 200, 300, 0, 100, 200, 300, 0, 100, 200, 300 };
		int[] ys = { 100, 100, 100, 100, 200, 200, 200, 200, 300, 300, 300, 300, 400, 400, 400, 400 };
		//
		StringBuilder sb = new StringBuilder();
		Calculator2 cal=new Calculator2();
		for (int i = 0; i < names.length; i++) {
			JButton btn1=new JButton(names[i]);
			//这个是控件的位置
			btn1.setBounds(xs[i], ys[i], 100, 100);
			//点击事件
			btn1.setActionCommand(names[i]);// 区分不同按钮
			//相当于匿名内部类对象
			btn1.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					//这个是一点击以后能获取到的内容
					String action =e.getActionCommand();
					System.out.println(action);
					/*
					 * 第一个运算数如何确定 输入运算符时，那么第一个运算数表示输入完毕 第二个运算数如何确定 输入=号的时候
					 * 
					 */
					
					if (isMark(action)) {
						cal.setX(lbResult.getText());
						cal.setMarke(action);
						sb.delete(0, sb.length());
					}else if("=".equals(action)) {
						cal.setY(lbResult.getText());
						lbResult.setText(cal.reture() + "");
						cal.setX(cal.reture() + "");
					}else {
						//拼接action，到StringBuilder
						sb.append(action);
						lbResult.setText(sb.toString());
					}
				}
			});
			add(btn1);
		}
		setVisible(true);
	}
	public boolean isMark(String str) {
		if (str==null|| str.length()==0) {
			return false;
		}
		str=str.charAt(0) +"";
		return "+-*/".contains(str);
	}

}
